﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XXZPrint.Models.Entity;

namespace XXZPrint.Models.DataOperation
{
    public class C_Do_XzdUser
    {
        /// <summary>
        /// 使用新中大的用户系统登录
        /// </summary>
        /// <param name="usercode">用户名称<para>可以是数据库ID，也可以是用户登录名</para></param>
        /// <param name="password">用户密码</param>
        /// <returns>返回值<para>-1:表示数据库错误；0:表示登录成功；1：表示用户不存在；2：表示密码错误</para></returns>
        public int CheckUserPassWord(string usercode, string password)
        {
            try
            {
                using (C_DbContext iDbContext = new C_DbContext("XZDCon"))
                {
                    var iData = iDbContext.DbContext.Query<secuser>()
                        .Where(w => w.logid == usercode || w.u_name == usercode)
                        .Select(s => new { s.logid, s.pwd })
                        .FirstOrDefault();
                    if ((iData == null) || string.IsNullOrEmpty(iData.logid)) return 1;

                    string ipassword = DecodePassword(iData.pwd, 128);
                    return ipassword == password ? 0 : 2;
                }
            }
            catch
            {
                return -1;
            }
        }

        private string DecodePassword(string aPassword, int aLen)
        {
            string str2;
            int num2;
            if (string.IsNullOrEmpty(aPassword))
            {
                return aPassword;
            }
            if (aLen < aPassword.Length)
            {
                aLen = aPassword.Length;
            }
            else if (aPassword.Length != aLen)
            {
                return aPassword;
            }
            int startIndex = aPassword.LastIndexOf('a') + 1;
            string str3 = aPassword.Substring(startIndex);
            int num = Convert.ToInt32(aPassword[0]) - 40;
            string str = "";
            for (num2 = 0; num2 < (aLen - startIndex); num2++)
            {
                str2 = aPassword.Substring(num - 1, 1);
                str = str + str2;
                num += 3;
            }
            for (num2 = 0; num2 < (aLen - startIndex); num2++)
            {
                if (str3.Substring(num2, 1) == "1")
                {
                    str2 = str[num2].ToString();
                    str = str.Remove(num2, 1).Insert(num2, str2.ToUpper());
                }
            }
            return str;
        }
    }
}